const app = getApp();
var md5 = require('../../utils/md5');
var config = require('../../utils/parts');
var requestUrl = getApp().request("url");
var header = getApp().request("header");
var status=1;      //定义抽取状态
Page({
  data: {
    config: config,//配件表
    partsName: '',//配件名称
    partsScore: 0,//配件评分
    oldCarList: 0,//原配件列表
    partsIntro: '',//配件介绍
    partsImgUrl: '',//配件图片
    nowScore: 0,//装载后的新评分
    scoreAddition: '',//新配件加成分
    choseLeftNum: 0,//剩余可抽取次数
    partsLevel: '', //5星130  4星100 3星80  2星60 1星30
    baseRequestUrl: config.apiUrl,//线上接口地址                
    baseImgUrl: config.imgUrl,//图片地址
    first: "",
    second: "",
    starLevel:"",
    time:"",
    luckDraw:false,
    ssr_ani: false,
    turnOver:false,       //翻转抽图鉴
    btn_image:"chose-one-more-on"
  },
  onLoad: function () {
    this.pageInfoInit(); 
  },
  onShow:function(){
    wx.showShareMenu({
      withShareTicket: true
    });
  },
  onShareAppMessage:function(){
    var that = this;
    //是否选车
    var fightCarTypeId = app.globalData.fightCarTypeId;
    //随机一句宣言
    var declaration = getApp().Refit();
    var myRefitTxt = Math.floor(Math.random() * declaration.length);
    
    if (fightCarTypeId == 0) {
      return {
        title: getApp().shareTitle1(),
        path: "/pages/index/index"
      }
    } else {
      return {
        title: getApp().shareTitle2(),
        path: "/pages/openShare/openShare?shareId=" + app.globalData.session_key.userId + "&carTypeId=" + fightCarTypeId + "&shareRefitNum=" + myRefitTxt + "&carName=SUV概念车",
        success: (re) => {
          if (Object.keys(re).length == 1) {
            return
          }
          var ticket = re.shareTickets[0];
          wx.getShareInfo({
            shareTicket: ticket,
            success: function (Re) {
              console.log(Re)
              var encryptedData = Re.encryptedData;
              var iv = Re.iv;
              //请求分享接口加次数
              wx.showLoading({
                title: '',
                mask:true
              });
              wx.request({
                url: requestUrl + 'shareGroupAddDrawNum',
                method: "POST",
                data: { userId: app.globalData.session_key.userId, salt: app.globalData.session_key.salt, encryptedData: encryptedData, iv: iv },
                header: header,
                success: function (Res) {
                  console.log(Res);
                  if (Res.data.code == 200) {
                    //当日剩余抽取次数减去一
                    var shareLeftN = app.globalData.shareLeftN;
                    shareLeftN--;
                    app.globalData.shareLeftN = shareLeftN;
                    //剩余抽取次数加3次
                    var drawLeftN = app.globalData.drawLeftN;
                    drawLeftN += 3;
                    app.globalData.drawLeftN = drawLeftN;
                    //页面分享进度减一
                    // var shareProgress = that.data.shareProcess;
                    //  shareProgress++;
                    that.setData({
                      choseLeftNum: that.data.choseLeftNum+3
                    })

                  } else if (Res.data.code == 401 || Res.data.code == 301 || Res.data.code == 302) {
                    getApp().showModal("提交信息有误!")
                  } else if (Res.data.code == 304) {
                    //getApp().showModal("解密错误!")
                    getApp().sessionKey()
                  } else if (Res.data.code == 800) {
                    getApp().showModal(Res.data.data.msg);
                    wx.hideLoading();
                  }
                  wx.hideLoading();
                },
                fail:function(res){
                  console.log("分享加次数接口fail");
                  console.log(res)
                  wx.hideLoading();
                  getApp().showModal("网络错误，请重试");
                }
              })
            }
          })
        }
      }
    } 
  },
  pageInfoInit: function () {
    //如果是抽取过，就翻卡
    if (this.data.btn_image =="btn_turnOverCar"){
      var btnStatus = this.data.choseLeftNum == 0 ? "btn-now-repack" :"chose-one-more-on"
      this.setData({
        btn_image: btnStatus,
        turnOver:true
      });
      return false;
    }
    var _this = this;
    var salt, userId, drawLeftN, nowScore, oldCarList;
    try {
      salt = app.globalData.session_key.salt;
      userId = app.globalData.session_key.userId;
      drawLeftN = app.globalData.drawLeftN;
      nowScore = app.globalData.score;
      oldCarList = app.globalData.car;

      if (salt && userId && drawLeftN >= 0 && nowScore >= 0 && oldCarList) {
        // Do something with return value
        _this.setData({
          choseLeftNum: drawLeftN,
          nowScore: nowScore,
          oldCarList: oldCarList
        })
        if (drawLeftN > 0) {
          this.luckDraw({ userId: app.globalData.session_key.userId, salt: app.globalData.session_key.salt });
          // this.setData({
          //     starLevel: ""
          // });
            
        } else {
          if (app.globalData.fightCarTypeId==0){
            getApp().showModal("请先购买车辆哦！")
          }else{
            wx.redirectTo({
              url: '../repack/repack'
            });
          }
          
        }
      } else {
        console.log('%c salt:' + salt + '\n', 'background:rgba(0,0,0,0.1);color:red');
        console.log('%c userId:' + userId + '\n', 'background:rgba(0,0,0,0.1);color:red');
        console.log('%c drawLeftN:' + drawLeftN + '\n', 'background:rgba(0,0,0,0.1);color:red');
        console.log('%c nowScore:' + nowScore + '\n', 'background:rgba(0,0,0,0.1);color:red');
        console.log('%c oldCarList:' + oldCarList + '\n', 'background:rgba(0,0,0,0.1);color:red');
      }
    } catch (e) {
      // Do something when catch error
      console.log('%c' + e, 'background:rgba(0,0,0,0.1);color:red');
    }
  },
  luckDraw: function (param) {
    var _this = this;
    var depot = app.globalData.depot;
    if (Object.keys(depot).length >= 48) {
      wx.showToast({
        title: '仓库已满,请先卖出多余配件',
        icon: 'none'
      })
      return false;
    };
    this.setData({
      ssr_ani: false
    });
    wx.showLoading({
      title: '',
      mask:true
    });
    wx.request({
      url: this.data.baseRequestUrl + 'luckDraw',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: param,
      success: function (res) {
        if (res.statusCode != 200) {
          wx.hideLoading();
          getApp().showModal("服务器异常");
          return
        }
        wx.hideLoading();
        _this.pageRender(res.data);
      },
      fail:function(res){
        console.log("抽卡fail");
        console.log(res);
        wx.hideLoading();
        getApp().showModal("网络超时，请检查您的网络");
      }
    })
  },
  pageRender: function (obj) { 
    var _this=this;
    switch (obj.code) {
      case 200:
      var str = obj.data.parts;
      var getcolor = null;
      if (str[0] == "a" || str[0] == "h") {
        getcolor = 0;
      } else {
        getcolor = config.getColorAddition(str[2]);
      }
      var url = this.data.baseImgUrl + '/parts/' + str[0] + '/' + str + '_small.png?111',
          level = str[1].toString() * 25 + 'rpx',
          score = config.getPartsScore(str[1], getcolor, config.getBaseAttribute(str[0], str[1])),
          intro = '',
          name = '';
        //抽取动画
        _this.setData({
          first: 1,
          second: 2,
          ssr_ani:true
        });
        console.log(str[1].toString()+"车件星级")
        if (str[0] == 'h') {
          intro = config[str[0]][str[1]][str[2]].intro;
          name = config[str[0]][str[1]][str[2]].name;
        } else if (str[0]=="a"){
          intro = config[str[0]][str[1]].intro;
          name = config[str[0]][str[1]].name;
        } 
        else {
          intro = config[str[0]][str[1]].intro;
          name = config[str[0]][str[1]].name + '（' + config.color[str[2] - 1] + '）';
        }
        //获取原配件
        var oldParts = this.data.oldCarList[0][str[0]], addition = '';
        var getcolor2 = null;
        if (oldParts[0] == "a" || oldParts[0] == "h") {
          getcolor2 = 0;
        } else {
          getcolor2 = config.getColorAddition(oldParts[2]);
        }
        var oldPartsScore = config.getPartsScore(oldParts[1], getcolor2, config.getBaseAttribute(oldParts[0], oldParts[1]));
        if (oldParts == '') {
          addition = score;
        } else {
          addition = score - oldPartsScore;
        }
        var num = this.data.choseLeftNum - 1;
        this.setData({
          partsImgUrl: url,
          partsName: name,
          partsLevel: level,
          partsScore: score,
          partsIntro: intro,
          scoreAddition: addition,
          choseLeftNum: num,
          starLevel: str[1].toString(),
          time: new Date().getTime(),
          btn_image:"btn_turnOverCar",
          turnOver:false
        });
        // wx.setStorage({
        //   key: 'drawLeftN',
        //   data: num,
        //   success: function (res) {

        //   }
        // })
        app.globalData.drawLeftN=num;
        _this.updateDepot(str);
        break;
      case 303:
        wx.showToast({
          title: '仓库已满,请先卖出多余配件',
          icon: 'none'
        });
        _this.setData({
          luckDraw: false
        });
        break;
      case 800:
        getApp().showModal(obj.data.msg);
        wx.hideLoading();
        break;
      default:
        console.log('%c抽配件接口返回错误' + obj.code, 'background:rgba(0,0,0,0.1);color:red');
        _this.setData({
          luckDraw: false
        });
    }
  },
  aniEnd: function () {
    this.setData({
      first: "",
      second: ""
    });
  },
  updateDepot: function (str) {

    var depotObj = app.globalData.depot;
    if (!depotObj) depotObj = {};

    if (depotObj[str]) {
      depotObj[str] = depotObj[str] + 1;
    } else {
      depotObj[str] = 1;
    }
    app.globalData.depot = depotObj;
  },
  setStorage: function (name, data) {
    //设置本地存储
    wx.setStorage({
      key: name,
      data: data,
      success: function () {
        console.log("%c存储用户" + name + "成功", 'background:#017b40;color:#fff');
      },
      fail: function (res) {
        console.log('%c存储用户' + name + '失败!\n' + res, 'background:rgba(0,0,0,0.1);color:red');
      }
    })
  },
  back: function () {
    //返回上一页
    wx.navigateBack({
      delta: 1
    })
  },
  //翻转抽牌
  btn_turnOver(){
    this.setData({
      turnOver:true
    })
  }
})